package com.bx.implatform.rabbitmq;

/**
 * @ClassName: MsgProducer
 * @Description:
 * @Author guochuang
 * @Date 2021/10/25
 * @Version 1.0
 */

import com.bx.imcommon.model.IMRecvInfo;
import com.bx.implatform.util.JsonXMLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

//消息的生产者
@Component
public class MsgProducer implements RabbitTemplate.ConfirmCallback {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MsgProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }

    public void sendSms(IMRecvInfo imRecvInfo) {
        try{
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            //把消息放入ROUTINGKEY_A对应的队列当中去，对应的是队列A
                logger.info(">>>>>>>>>>>>>>require is begin：{}",imRecvInfo);
            rabbitTemplate.convertAndSend("my-mq-exchange_im_private_message_C", null, JsonXMLUtils.obj2json(imRecvInfo),correlationId);
            logger.info("请求已入队列>>>>>>>>>>>>>");
        } catch (AmqpException e) {
            logger.error("请求发送异常："+e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        logger.info(" 回调id:" + correlationData);
        if (ack) {
            logger.info("消息成功消费:"+correlationData.getId());
        } else {
            logger.info("消息消费失败:" + cause);
        }
    }
}
